package com.kye.express.business.online_pay.history;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.widget.Toast;

import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.datetimepicker.DateTimePicker;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.databinding.ActivityOnlinePayBinding;
import com.kye.express.databinding.ActivityOnlinePayHistoryBinding;
import com.kye.express.utils.DateTimeUtils;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.online.GetPayRecordResultBean;
import com.kye.model.bean.user.User;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.Date;
import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 支付记录
 */
public class OnlinePayHistoryActivity extends BaseToolbarActivity implements OnlinePayHistoryActivityContract.OnlinePayHistoryActivityView {
    private final String DATA_FORMAT = "yyyy-MM-dd";
    private ActivityOnlinePayHistoryBinding mBinding;

    protected MultiTypeAdapter mAdapter;
    protected Items mDatas = new Items();
    private String mStartTime = "";
    private String mEndTime = "";
    private Dialog mLoadingDialog;

    private OnlinePayHistoryActivityContract.OnlinePayHistoryActivityViewPresenter mPresenter;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, OnlinePayHistoryActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_online_pay_history);
        mPresenter = new OnlinePayHistoryActivityContract.OnlinePayHistoryActivityViewPresenter(this);
        mPresenter.bind(this);
        setUpToolbar((Toolbar) findViewById(R.id.toolbar));
        setTitle(getString(R.string.online_pay_pay_record));
        initView();
        initEvent();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.unbind();
        }
    }

    private void initView() {
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(GetPayRecordResultBean.PayRecordBean.class, new OnlinePayHistoryListItemViewBinder(this));
        mBinding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
        mBinding.recyclerview.setHasFixedSize(true);
        mBinding.recyclerview.setNestedScrollingEnabled(false);
        RecyclerViewDivider.with(this)
                .color(getResources().getColor(R.color.grey))
                .size(ScreenUtils.dp2px(this, 1))
                .hideLastDivider()
                .build()
                .addTo(mBinding.recyclerview);
        mBinding.recyclerview.setItemAnimator(new DefaultItemAnimator());
        mAdapter.setItems(mDatas);
        mBinding.recyclerview.setAdapter(mAdapter);
        mBinding.refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPresenter.loadDatas(false, false, mStartTime, mEndTime);
            }

            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                mPresenter.loadDatas(false, true, mStartTime, mEndTime);
            }

        });
    }

    private void initEvent() {
        RxView.clicks(mBinding.btnQuery)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (TextUtils.isEmpty(mStartTime) || TextUtils.isEmpty(mEndTime)) {
                            showToast(getString(R.string.invoice_online_time_null));
                            return;
                        }
                        long endTime = DateTimeUtils.getSimpleLongDDTime(mEndTime);
                        long startTime = DateTimeUtils.getSimpleLongDDTime(mStartTime);
                        if (startTime > endTime) {
                            showToast(getString(R.string.invoice_online_start_time_error));
                            return;
                        }
                        long s = (endTime - startTime) / (1000 * 60 * 60 * 24);
                        if (s > 31) {//是否大于一个月
                            showToast(getString(R.string.invoice_online_time_limits_error));
                            return;
                        }
                        mPresenter.loadDatas(true, false, mStartTime, mEndTime);
                    }
                });
        RxView.clicks(mBinding.tvDateFrom)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        selectDate(true);
                    }
                });
        RxView.clicks(mBinding.tvDateTo)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        selectDate(false);
                    }
                });
    }

    private void showToast(String message) {
        ToastManager.show(OnlinePayHistoryActivity.this, message, Toast.LENGTH_SHORT);
    }

    private void selectDate(boolean isFrom) {
        DateTimePicker.show(this, true, true, true, false, false, false, new DateTimePicker.DateTimeCallBack() {
            @Override
            public void callBack(Date date) {
                long selectLongTime = DateTimeUtils.getSimpleLongTime(DateTimeUtils.getStringDateByMounthDay(date.getTime()), DATA_FORMAT);
                long mCurrentLong = DateTimeUtils.getSimpleLongTime(DateTimeUtils.getStringDateByMounthDay(System.currentTimeMillis()), DATA_FORMAT);//当前时间
                if (selectLongTime > mCurrentLong) {
                    showToast(getString(R.string.invoice_online_time_max));
                } else {
                    String dateString = DateTimeUtils.getStringByDate(date);
                    if (isFrom) {
                        mStartTime = dateString;
                        mBinding.tvDateFrom.setText(dateString);
                    } else {
                        mEndTime = dateString;
                        mBinding.tvDateTo.setText(dateString);
                    }
                }
            }
        });
    }

    @Override
    public void onComplete(boolean isLoadMore) {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        if (isLoadMore) {
            mBinding.refreshLayout.finishLoadmore();
        } else {
            mBinding.refreshLayout.finishRefresh();
        }
    }

    @Override
    public void onLoading() {
        try {
            if (mLoadingDialog == null) {
                mLoadingDialog = new KyeProgressDialog.Builder(this)
                        .build();
            }
            mLoadingDialog.show();
        } catch (Exception e) {

        }
    }

    @Override
    public void onLoaded(GetPayRecordResultBean resultDatas, boolean isLoadMore) {
        if (resultDatas != null) {
            List<GetPayRecordResultBean.PayRecordBean> payRecordBeans = resultDatas.getPayRecord();
            if (payRecordBeans != null && payRecordBeans.size() > 0) {
                if (!isLoadMore) {
                    mDatas.clear();
                    mDatas.addAll(payRecordBeans);
                    mAdapter.notifyDataSetChanged();
                } else {
                    List<GetPayRecordResultBean.PayRecordBean> datas = (List<GetPayRecordResultBean.PayRecordBean>) mAdapter.getItems();
                    if (datas != null) {
                        int start = datas.size();
                        datas.addAll(payRecordBeans);
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }
        }
    }

    @Override
    public void onError(String msg, boolean isLoadMore) {
        ToastManager.show(this, msg, Toast.LENGTH_SHORT);
        if (isLoadMore) {
            mBinding.refreshLayout.finishLoadmore(false);
        } else {
            mBinding.refreshLayout.finishRefresh(false);
        }
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onUser(User user) {

    }
}
